package com.svs.framework.shiro.web.filter.online;

import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.svs.common.constant.ShiroConstants;
import com.svs.common.enums.OnlineStatus;
import com.svs.framework.shiro.session.OnlineSession;
import com.svs.framework.shiro.util.ShiroUtils;
import com.svs.framework.shiro.session.OnlineSessionDAO;
import com.svs.system.domain.SysUser;

/**
 * 自定义访问控制
 * 
 * @author dujianqiao
 */
public class LoginSessionFilter extends AccessControlFilter
{
    /**
     * 登录失效后返回到登录页面
     */
    @Value("${shiro.user.loginUrl}")
    private String loginUrl;

    @Autowired
    private OnlineSessionDAO onlineSessionDAO;

    /**
     * 表示是否允许访问；mappedValue就是[urls]配置中拦截器参数部分，如果允许访问返回true，否则false；
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception
    {
    	if (isLoginRequest(request, response)) {
            return true;
        } else {
	    	SysUser user = ShiroUtils.getSysUser();
	    	if(null==user){
	    		return false;
	    	}
	        return true;
        }
    }

    /**
     * 表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；如果返回false表示该拦截器实例已经处理了，将直接返回即可。
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
    {
        Subject subject = getSubject(request, response);
        if (subject != null)
        {
            subject.logout();
        }
        saveRequestAndRedirectToLogin(request, response);
        return true;
    }

    // 跳转到登录页
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException
    {
        WebUtils.issueRedirect(request, response, loginUrl);
    }
}
